<%@page import="util.UploadHelper"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.disk.*"%>
<%@page import="org.apache.commons.fileupload.*"%>
<%@page import="java.io.File"%>
<%@page import="java.util.*"%>
<%@page import="dao.UsersDao"%>
<%@page import="model.UsersModel"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%
try {
	//创建实体对象
	
	UsersModel model =new UsersModel();
	UploadHelper uploadHelper =new UploadHelper(request,response);
	ServletFileUpload upload = uploadHelper.getServletFileUpload();
	//将表单中的所有元素转换为FileItem对象，保存到List中
	List items = upload.parseRequest(request);
	//使用迭代器，遍历FileItem集合中的表单元素
	Iterator iter = items.iterator();
	while (iter.hasNext()) {
		//获取当前的表单元素
		FileItem item = (FileItem) iter.next();
		// 判断是否是file表单元素
		if (!item.isFormField()) {
			//获取源文件的文件名 2.jpg
			String originalFilename = item.getName();
			//获取源文件的扩展名
			String fileExtendName = originalFilename.substring(originalFilename.lastIndexOf("."));
			//将源文件保存到目标文件中
			String uploadPath = uploadHelper.getUploadPath();
			String destFileName = uploadHelper.getFileName();
			
			item.write(new File(uploadPath +destFileName + fileExtendName));
			//将文件名保存到实体对象中
			model.setHeaderimage(destFileName+fileExtendName);			
		} else {
			// 获得文件描述
			String fieldName =  item.getFieldName();
			if(fieldName.equals("username")){
				model.setUsername(item.getString("utf-8"));
			}else if(fieldName.equals("userpass")){
				model.setUserpass(item.getString("utf-8"));
			}else if(fieldName.equals("usertel")){
				model.setUsertel(item.getString("utf-8"));
			}
		}
	}
	//保存数据
	UsersDao dao =new UsersDao();
	 int res = dao.register(model);
	 if(res==0){
	 //注册失败,去注册界面，重新注册
	 response.sendRedirect("register.jsp");
	 }
	 else{
	 //注册成功，去登录界面
	 response.sendRedirect("login.jsp");
	 }
} catch (Exception e) {
	e.printStackTrace();
	response.sendRedirect("register.jsp");
}

%>